package singleton.type2;

/**
 * 饿汉式：静态代码块
 * 可能会导致内存浪费
 * @author yi qiang
 * @date 2021/5/2 22:07
 */
public class Singleton2 {

    public static void main(String[] args) {
        Singleton singleton=Singleton.getInstance();
        Singleton singleton2=Singleton.getInstance();
        System.out.println(singleton==singleton2);
    }


}

class Singleton{

    private  static  Singleton instance;

    //1.构造器私有化,使得外部不能通过new创建实例
    private Singleton(){
    }


    //2.本类内部创建一个实例
    static {
        instance=new Singleton();
    }

    //3.对外暴露一个公共的静态方法获取实例
    public static Singleton getInstance(){
        return instance;
    }
}
